package com.kool.kmqtt.server.failover;

import com.kool.kmqtt.server.ServerConfig;
import com.kool.kmqtt.server.repository.Repository;
import com.kool.kmqtt.server.repository.RepositoryFactory;

/**
 * @author luyu
 */
public class FailoverUtil {
    /**
     * 熔断检查，检查是否达到熔断条件
     *
     * @return
     */
    public static boolean check(String remoteAddress) {
        //熔断开关开启才执行
        if (ServerConfig.getInstance().getFailoverSwitch()) {
            Repository repository = RepositoryFactory.getRepository();
            Integer times = repository.getClientConnectErrorTimes(remoteAddress);
            if (times != null && times >= ServerConfig.getInstance().getFailoverThreshold()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 熔断计数，客户端连接错误次数自增1
     *
     * @param remoteAddress
     */
    public static void count(String remoteAddress) {
        //熔断开关开启才执行
        if (ServerConfig.getInstance().getFailoverSwitch()) {
            int timeoutSeconds = ServerConfig.getInstance().getFailoverCounterResetSeconds();
            Repository repository = RepositoryFactory.getRepository();
            repository.increaseFailoverCounter(remoteAddress, timeoutSeconds);
        }

    }
}
